using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace GPS
{
    public class GPSDevice
    {
        private System.IO.Ports.SerialPort bluetoothToSerial;
        

        public GPSDevice(string port,int baudrate)
        {
            bluetoothToSerial = new System.IO.Ports.SerialPort(port,baudrate);
            try
            {
                bluetoothToSerial.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("No pude abrir el GPS en el puerto"+ port +" "+ ex.ToString());
            }
        }
        public GPSDevice(string port)
        {
            bluetoothToSerial = new System.IO.Ports.SerialPort(port);
            bluetoothToSerial.BaudRate = 9600;
            try
            {
                bluetoothToSerial.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("No pude abrir el GPS en el puerto" + port + " " + ex.ToString());
            }
        }

        public bool ensureBluetoothIsOpen()
        {
            if (!bluetoothToSerial.IsOpen)
            {
                try
                {
                    bluetoothToSerial.Open();
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No pude abrir el GPS" + ex.ToString());
                    return false;
                }
            }
            return true;
        }


        public void closeBluetooth()
        {
            try
            {
                /* Close the damn thing */
                bluetoothToSerial.Close();
                return;
            }
            catch (Exception)
            {
                return;
            }
        }
        public bool IsOpen()
        {
            return bluetoothToSerial.IsOpen;
        }
        // public string ReadLine()
        // {
        //    return bluetoothToSerial.ReadLine();
        //}
        public void Close()
        {
            bluetoothToSerial.Close();
        }
        
        public GPSData getLatLong()
        {
            string line = bluetoothToSerial.ReadLine();
            while (!(line.StartsWith("$GPRMC")))
                line = bluetoothToSerial.ReadLine();
            return NMEAParser.parseFromRMC(line);
        }
    }
}
